#import "layer_library_experiment.h"

#define LIBRARY_EXPERIMENT_PIECE_WIDTH 83
#define LIBRARY_EXPERIMENT_PIECE_HEIGHT 94

#define PIECE_BACK_TO_HOLDER_SPEED 3000

#define COVER_OPEN_TIME 0.2f
#define COVER_CLOSE_TIME 0.2f

#if (HARD_WARE == HARD_WARE_IPHONE)
	#define LIBRARY_EXPRIMENT_TUTORIAL_FONT_SIZE 16
#elif (HARD_WARE == HARD_WARE_IPAD)
	#define LIBRARY_EXPRIMENT_TUTORIAL_FONT_SIZE 32
#endif

#if (HARD_WARE == HARD_WARE_IPHONE)
	#define LIBRARY_EXPRIMENT_ITEM_FONT_SIZE 12
#elif (HARD_WARE == HARD_WARE_IPAD)
	#define LIBRARY_EXPRIMENT_ITEM_FONT_SIZE 24
#endif

static ccColor3B EXPERIMENT_TEXT_COLOR = {219, 36, 36};

@implementation layer_library_experiment

@synthesize flagTouchLock = flagTouchLock_;
@synthesize flagFunctionLock = flagFunctionLock_;

- (id)initLayerLibraryExperiment
{
	int i, j;
	int _Index;
	CGPoint _Pos;
	CCSprite *_Background;
	CCSprite *_Frame;
	CCSprite *_Heart;
	CCSprite *_Box;
	CCMenuItemImage *_ItemShake;

	if ((self = [super init]))
	{
		self.isTouchEnabled = YES;

		/*load resource
		*/
		reLoadResource(&g_CfgLibraryExperimentResourceTable);

		/*background
		*/
		_Background = uiCreateImageObject(&g_CfgLibraryExperimentImageBackgournd, self);
		_Background.scaleX = g_ScrrenSize.width / _Background.contentSizeInPixels.width;
		_Background.scaleY = g_ScrrenSize.height / _Background.contentSizeInPixels.height;
		_Frame = uiCreateImageObject(&g_CfgLibraryExperimentImageContainerRune, self);
		_Heart = uiCreateImageObject(&g_CfgLibraryExperimentImageContainerHeart, self);

		containerRect_.center = _Heart.positionInPixels;
		containerRect_.size = _Heart.contentSizeInPixels;

		_Frame.opacity = 50;
		[_Frame runAction:[CCRepeatForever actionWithAction:[CCRotateBy actionWithDuration:1.0f angle:10]]];

		selectAPosition_ = ccp(_Heart.positionInPixels.x - 70, _Heart.positionInPixels.y);
		selectBPosition_ = ccp(_Heart.positionInPixels.x + 70, _Heart.positionInPixels.y);

		/*menu
		*/
		_ItemShake = uiCreateMenuItemImageObject(&g_CfgLibraryExperimentItemShake, self, @selector(CallBackMenuItemShake:));

		itemBack_ = CREATE_BTN_BACK(CallBackMenuItemBack);
		itemBack_.anchorPoint = ccp(0.9f, 0.0f);
		itemBack_.positionInPixels = ccp(g_ScrrenSize.width, 0.0f);

		uiNodeAddMenu(self, CGPointZero, _ItemShake, itemBack_, nil);

		/*clear holder
		*/
		memset(holder_, 0, sizeof holder_);
		for (i = 0; i < EXPERIMENT_HOLDER_COUNT; i++)
		{
			holder_[i].piece_id = -1;
		}

		/*initialization holder position
		*/
		_Index = 0;
		for (i = 0; i < 2; i++)
		{
			_Pos.y = g_CfgLibraryExperimentImageBoxBasePosition.y - i * g_CfgLibraryExperimentImageBoxSize.height;
			for (j = 0; j < 4; j++)
			{
				_Pos.x = g_CfgLibraryExperimentImageBoxBasePosition.x + j * g_CfgLibraryExperimentImageBoxSize.width;
				_Box = [CCSprite spriteWithSpriteFrameName:[NSString stringWithUTF8String:g_CfgLibraryExperimentImageBoxPath]];
				[self addChild:_Box];
				_Box.positionInPixels = _Pos;
				holder_[_Index].position = _Pos;
				_Index++;
			}
		}

		/*load piece to holder
		*/
		_Index = 0;
		for (i = 0; i < ITEM_TYPE_COUNT; i++)
		{
			if (g_RecordPieceCount[i] > 0)
			{
				[self HolderLoadPiece:_Index And:i];
				_Index++;
			}
		}

		/*flag
		*/
		flagTouchLock_ = false;
		flagFunctionLock_ = false;

		selectId_ = -1;
		selectPiece_ = nil;
		selectIdA_ = -1;
		selectIdB_ = -1;
		selectPieceA_ = nil;
		selectPieceB_ = nil;

		actionIdA_ = -1;
		actionIdB_ = -1;
		preview_ = nil;

		if (g_RecordExperimentTutorial)
		{
			g_RecordExperimentTutorial = false;
			preview_ = [[sprite_library_experiment_preview alloc] initSpriteLibraryExperimentPreViewToturial];
			[self addChild:preview_];
			[preview_ release];
			preview_.positionInPixels = g_ScrrenCenter;
			RecordSave();
		}
	}
	return self;
}

- (void)dealloc
{
	/*reset piece count
	*/
	if (selectId_ != -1)
	{
		g_RecordPieceCount[selectId_]++;
	}
	if (selectIdA_ != -1)
	{
		g_RecordPieceCount[selectIdA_]++;
	}
	if (selectIdB_ != -1)
	{
		g_RecordPieceCount[selectIdB_]++;
	}

	/*release resource
	*/
	reFreeResource(&g_CfgLibraryExperimentResourceTable);

	[super dealloc];
}

- (void)ccTouchesBegan:(NSSet *)Touch withEvent:(UIEvent *)Event
{
	int i;
	CGPoint _Point;
	UITouch *_Touch;
	UICenterRect _Rect;

	if (flagTouchLock_)
	{
		return;
	}
	if (nil != preview_)
	{
		return;
	}

	_Touch = [Touch anyObject];
	_Point = [[CCDirector sharedDirector] convertToGL:[_Touch locationInView:[_Touch view]]];
	_Point = ConvertPositionToPositionInPixels(_Point);

	/*check select holder item
	*/
	for (i = 0; i < EXPERIMENT_HOLDER_COUNT; i++)
	{
		if (holder_[i].piece_id == -1)
		{
			continue;
		}

		_Rect.center = holder_[i].position;
		_Rect.size = CGSizeMake(LIBRARY_EXPERIMENT_PIECE_WIDTH, LIBRARY_EXPERIMENT_PIECE_HEIGHT);
		if (uiPointInCenterRect(_Point, _Rect) && (g_RecordPieceCount[holder_[i].piece_id] > 0))
		{
			g_RecordPieceCount[holder_[i].piece_id]--;
			if (g_RecordPieceCount[holder_[i].piece_id] == 0)
			{
				selectId_ = holder_[i].piece_id;
				selectPiece_ = holder_[i].piece;

				/*clear holder
				*/
				holder_[i].piece_id = -1;
				holder_[i].piece = nil;
				[self removeChild:holder_[i].label cleanup:TRUE];
				holder_[i].label = nil;
				goto END_;
			}
			else
			{
				selectId_ = holder_[i].piece_id;
				selectPiece_ = [CCSprite spriteWithSpriteFrameName:[NSString stringWithUTF8String:g_CfgPieceTable.find(selectId_)->second.path]];
				[self addChild:selectPiece_];
				[self HolderLoadPiece:i And:selectId_];
				goto END_;
			}
		}
	}

	/*check select piece A
	*/
	_Rect.center = selectPieceA_.positionInPixels;
	_Rect.size = CGSizeMake(LIBRARY_EXPERIMENT_PIECE_WIDTH, LIBRARY_EXPERIMENT_PIECE_HEIGHT);
	if (uiPointInCenterRect(_Point, _Rect))
	{
		[selectPieceA_ stopAllActions];
		selectId_ = selectIdA_;
		selectPiece_ = selectPieceA_;
		selectIdA_ = -1;
		selectPieceA_ = nil;
		goto END_;
	}

	/*check select piece B
	*/
	_Rect.center = selectPieceB_.positionInPixels;
	_Rect.size = CGSizeMake(LIBRARY_EXPERIMENT_PIECE_WIDTH, LIBRARY_EXPERIMENT_PIECE_HEIGHT);
	if (uiPointInCenterRect(_Point, _Rect))
	{
		[selectPieceB_ stopAllActions];
		selectId_ = selectIdB_;
		selectPiece_ = selectPieceB_;
		selectIdB_ = -1;
		selectPieceB_ = nil;
		goto END_;
	}

END_:
	if (selectPiece_ != nil)
	{
		selectPiece_.positionInPixels = _Point;
	}
}

- (void)ccTouchesMoved:(NSSet *)Touch withEvent:(UIEvent *)Event
{
	CGPoint _Point;
	UITouch *_Touch;

	if (flagTouchLock_)
	{
		return;
	}
	if (nil != preview_)
	{
		return;
	}

	if (selectId_ == -1)
	{
		return;
	}

	_Touch = [Touch anyObject];
	_Point = [[CCDirector sharedDirector] convertToGL:[_Touch locationInView:[_Touch view]]];
	_Point = ConvertPositionToPositionInPixels(_Point);
	selectPiece_.positionInPixels = _Point;
}

- (void)ccTouchesEnded:(NSSet *)Touch withEvent:(UIEvent *)Event
{
	int _HolderIndex;
	CGPoint _Point;
	UITouch *_Touch;
	CCSequence *_Seq;
	CCCallFuncN *_CallBackMoveOver;

	if (flagTouchLock_)
	{
		return;
	}

	if (nil != preview_)
	{
		/*effect
		*/
		EffectButton();

		[preview_ ActionClose];
		return;
	}

	if (selectId_ == -1)
	{
		return;
	}

	_Touch = [Touch anyObject];
	_Point = [[CCDirector sharedDirector] convertToGL:[_Touch locationInView:[_Touch view]]];
	_Point = ConvertPositionToPositionInPixels(_Point);

	if (uiPointInCenterRect(_Point, containerRect_))
	{
		if (selectIdA_ == -1)
		{
			selectIdA_ = selectId_;
			selectPieceA_ = selectPiece_;
			selectId_ = -1;
			selectPiece_ = nil;
			[selectPieceA_ runAction:tcCreateActionMove(selectPieceA_.positionInPixels, selectAPosition_, 1000.0f)];
		}
		else if (selectIdB_ == -1)
		{
			selectIdB_ = selectId_;
			selectPieceB_ = selectPiece_;
			selectId_ = -1;
			selectPiece_ = nil;
			[selectPieceB_ runAction:tcCreateActionMove(selectPieceB_.positionInPixels, selectBPosition_, 1000.0f)];
		}
		else
		{
			goto BACK_;
		}
	}
	else
	{
BACK_:
		_HolderIndex = [self GetHolderIndex:selectId_];
		_CallBackMoveOver = [CCCallFuncN actionWithTarget:self selector:@selector(CallBackPieceMoveBackOver:)];
		_Seq = [CCSequence actions:tcCreateActionMove(selectPiece_.positionInPixels, holder_[_HolderIndex].position, PIECE_BACK_TO_HOLDER_SPEED), _CallBackMoveOver, nil];
		[selectPiece_ runAction:_Seq];
		flagTouchLock_ = true;
	}
}

- (void)HolderLoadPiece:(int)HolderIndex And:(int)id
{
	if (g_RecordPieceCount[id] == 0)
	{
		return;
	}

	holder_[HolderIndex].piece_id = id;

	/*piece
	*/
	if (holder_[HolderIndex].piece == nil)
	{
		holder_[HolderIndex].piece = [CCSprite spriteWithSpriteFrameName:[NSString stringWithUTF8String:g_CfgPieceTable.find(id)->second.path]];
		[self addChild:holder_[HolderIndex].piece];
		holder_[HolderIndex].piece.positionInPixels = holder_[HolderIndex].position;
	}
	else
	{
		[holder_[HolderIndex].piece setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithUTF8String:g_CfgPieceTable.find(id)->second.path]]];
	}

	/*lable
	*/
	if (holder_[HolderIndex].label == nil)
	{
		holder_[HolderIndex].label = [CCLabelTTF labelWithString:@"A" fontName:@"Helvetica-Bold" fontSize:32];
		[self addChild:holder_[HolderIndex].label];
		holder_[HolderIndex].label.positionInPixels = ccpAdd(holder_[HolderIndex].position, ccp(30, -30));
		holder_[HolderIndex].label.color = EXPERIMENT_TEXT_COLOR;
	}
	if (g_RecordPieceCount[id] > 1)
	{
		[holder_[HolderIndex].label runAction:[CCShow action]];
		[holder_[HolderIndex].label setString:[NSString stringWithFormat:@"%d", g_RecordPieceCount[id]]];
	}
	else
	{
		[holder_[HolderIndex].label runAction:[CCHide action]];
	}
}

- (void)HolderClear:(SHolder *)Holder
{
	if (Holder->piece_id != -1)
	{
		Holder->piece_id = -1;
		[self removeChild:Holder->piece cleanup:TRUE];
		Holder->piece = nil;
		[self removeChild:Holder->label cleanup:TRUE];
		Holder->label = nil;
	}
}

- (int)GetHolderIndex:(int)PieceId
{
	int i;

	/*check same piece id holder
	*/
	for (i = 0; i < EXPERIMENT_HOLDER_COUNT; i++)
	{
		if (holder_[i].piece_id == PieceId)
		{
			return i;
		}
	}

	/*get first empty holder
	*/
	for (i = 0; i < EXPERIMENT_HOLDER_COUNT; i++)
	{
		if (holder_[i].piece_id == -1)
		{
			return i;
		}
	}

	return -1;
}

- (void)SelectBackToHolder:(int)PieceId
{
	int _HolderIndex;

	_HolderIndex = [self GetHolderIndex:PieceId];
	if (-1 == _HolderIndex)
	{
		return;
	}
	[self HolderLoadPiece:_HolderIndex And:PieceId];
}

- (void)CheckAndCreate
{
	std::list<SBaseDataFormula>::iterator _Iter;
	int _Type;
	int _Id;
	int _Count;
	int _A, _B;

	_Type = -1;
	_Id = -1;
	_Count = 1;

	/*check
	*/
	_Iter = g_CfgFormulaTable.begin();
	for (; _Iter != g_CfgFormulaTable.end(); _Iter++)
	{
		_A = _Iter->component_a;
		_B = _Iter->component_b;
		if ((_A == actionIdA_) && (_B == actionIdB_))
		{
			goto MAKE_;
		}
		if ((_B == actionIdA_) && (_A == actionIdB_))
		{
			goto MAKE_;
		}
	}

	/*not find
	*/
	return;

	/*find and make
	*/
MAKE_:
	_Type = _Iter->product_type;
	_Id = _Iter->product_id;

	/*record
	*/
	switch (_Type)
	{
	case ID_TYPE_WEAPON:
		if (g_RecordWeapLock[_Id])
		{
			g_RecordWeapLock[_Id] = false;
		}
		else
		{
			_Type = ID_TYPE_ITEM;
			_Id = rand() % ITEM_TYPE_COUNT;
			if (_A + _B < 6)
			{
				_Count = 2;
			}
			else if (_A + _B == 6)
			{
				_Count = 3;
			}
			else if (_A + _B == 7)
			{
				_Count = 4;
			}
			else if (_A + _B == 8)
			{
				_Count = 5;
			}
			else if (_A + _B == 9)
			{
				_Count = 7;
			}
			else if (_A + _B <= 11)
			{
				_Count = 10;
			}
			else if (_A + _B == 12)
			{
				_Count = 15;
			}
			else
			{
				_Count = 0;
			}
			_Type = ID_TYPE_ITEM;
			g_RecordItemCount[_Id] += _Count;
		}
		break;
	case ID_TYPE_ITEM:
		if (g_RecordItemLock[_Id])
		{
			g_RecordItemLock[_Id] = false;
		}
		g_RecordItemCount[_Id]++;
		break;
	case ID_TYPE_EXHIBITION:
		if (g_RecordExhibitionElementLock[_Id])
		{
			g_RecordExhibitionElementLock[_Id] = false;
		}
		else
		{
			_Type = ID_TYPE_ITEM;
			_Id = rand() % ITEM_TYPE_COUNT;
			if (_A + _B < 6)
			{
				_Count = 2;
			}
			else if (_A + _B == 6)
			{
				_Count = 3;
			}
			else if (_A + _B == 7)
			{
				_Count = 4;
			}
			else if (_A + _B == 8)
			{
				_Count = 5;
			}
			else if (_A + _B == 9)
			{
				_Count = 7;
			}
			else if (_A + _B <= 11)
			{
				_Count = 10;
			}
			else if (_A + _B == 12)
			{
				_Count = 15;
			}
			else
			{
				_Count = 0;
			}
			_Type = ID_TYPE_ITEM;
			g_RecordItemCount[_Id] += _Count;
		}
		break;
	default:;
	}

	/*preview
	*/
	preview_ = [[sprite_library_experiment_preview alloc] initSpriteLibraryExperimentPreView:_Type And:_Id And:_Count];
	[self addChild:preview_];
	[preview_ release];
	preview_.positionInPixels = g_ScrrenCenter;

	RecordSave();
}

- (void)PreviewOver
{
	[self removeChild:preview_ cleanup:YES];
	preview_ = nil;
}

- (void)CallBackActionShake:(id)Sender
{
	CCSequence *_Seq;
	CCCallFuncN *_CallBack;

	if (flagFunctionLock_)
	{
		return;
	}
	if ((-1 == selectIdA_) || (-1 == selectIdB_))
	{
		return;
	}

	flagTouchLock_ = true;

	_CallBack = [CCCallFuncN actionWithTarget:self selector:@selector(CallBackSelectPieceADisapper:)];
	_Seq = [CCSequence actions:[CCScaleTo actionWithDuration:0.15 scaleX:0.01 scaleY:3], _CallBack, nil];
	[selectPieceA_ runAction:_Seq];

	_CallBack = [CCCallFuncN actionWithTarget:self selector:@selector(CallBackSelectPieceBDisapper:)];
	_Seq = [CCSequence actions:[CCScaleTo actionWithDuration:0.15 scaleX:0.01 scaleY:3], _CallBack, nil];
	[selectPieceB_ runAction:_Seq];

	actionIdA_ = selectIdA_;
	actionIdB_ = selectIdB_;
	[self runAction:tcCreateActionCallBack(self, 0.15, @selector(CallBackCheckAndCreate:))];
}

- (void)CallBackMenuItemShake:(id)Sender
{
	if (flagFunctionLock_)
	{
		return;
	}

	/*effect
	*/
	EffectButton();

	[self CallBackActionShake:nil];
}

- (void)CallBackMenuItemBack:(id)Sender
{
	CCSequence *_Seq;
	id _Action;
	CCCallFuncN *_CallBack;

	if (flagFunctionLock_)
	{
		return;
	}

	/*effect
	*/
	EffectButton();

	/*action
	*/
	flagTouchLock_ = true;
	flagFunctionLock_ = true;
	_Action = [action_move_in_pixel actionWithDuration:BTN_MOVE_TIME position:ccp(g_ScrrenSize.width + itemBack_.contentSizeInPixels.width, 0.0f)];
	_CallBack = [CCCallFuncN actionWithTarget:self selector:@selector(CallBackMenuItemBackActionOver:)];
	_Seq = [CCSequence actions:_Action, _CallBack, nil];
	[itemBack_ runAction:_Seq];
}

- (void)CallBackMenuItemBackActionOver:(id)Sender
{
	[g_SceneLibrary SetState:SCENE_LIBRARY_STATE_MAIN];
}

- (void)CallBackPieceMoveBackOver:(id)Sender
{
	g_RecordPieceCount[selectId_]++;
	[self SelectBackToHolder:selectId_];
	[self removeChild:selectPiece_ cleanup:TRUE];
	selectId_ = -1;
	selectPiece_ = nil;
	flagTouchLock_ = false;
}

- (void)CallBackSelectPieceADisapper:(id)Sender
{
	flagTouchLock_ = false;
	[self removeChild:selectPieceA_ cleanup:true];
	selectIdA_ = -1;
	selectPieceA_ = nil;
}

- (void)CallBackSelectPieceBDisapper:(id)Sender
{
	flagTouchLock_ = false;
	[self removeChild:selectPieceB_ cleanup:true];
	selectIdB_ = -1;
	selectPieceB_ = nil;
}

- (void)CallBackCheckAndCreate:(id)Sender
{
	[self CheckAndCreate];
}

@end